var dojoConfig = {
	parseOnLoad : true
};
require([ "dijit/Dialog", "dijit/form/TextBox", "dijit/form/Button" ]);
require([ "dojo/query", "dojo/NodeList-traverse" ]);
require([ "dojo/parser", "dijit/TitlePane" ]);
dojo.require("dijit/dijit"); // optimize: load dijit layer
dojo.require("dojox/grid/DataGrid");
dojo.require("dojo/data/ItemFileWriteStore");
dojo.require("dijit/layout/BorderContainer");
dojo.require("dijit/layout/ContentPane");
dojo.require("dijit/Tree");
dojo.require("dijit/tree/ForestStoreModel");
dojo.require("dojo/store/JsonRest");
dojo.require("dojo/store/Observable");
dojo.require("dijit/tree/dndSource");
dojo.require("dijit/form/ValidationTextBox");
//lazy load tree
dojo.declare("dojox/grid/SlowFileWriteStore", dojo.data.ItemFileWriteStore, {
	_fetchItems : function( /*Object*/keywordArgs,
	/*Function*/findCallback,
	/*Function*/errorCallback) {
		setTimeout(dojo.hitch(this, function() {
			dojo.data.ItemFileWriteStore.prototype._fetchItems.call(this,
					keywordArgs, findCallback, errorCallback);
		}), 10000);
	}
});

//Get TestFunName
var testfunctionName;
var Tcparent;
function send(mname,parent) {
	testfunctionName = mname;
	Tcparent =parent;

}

////addTestCase
//function addTestCase() {
//
//	var TestCaseNum = document.getElementById("TestCaseNum").value;
//	var TestCaseName = document.getElementById("TestCaseName").value;
//	var Description = document.getElementById("Description").value;
//	var Type = document.getElementById("Type").value;
//    var parent =testfunctionName;
//	var gridData = {
//		'testcaseNum' : TestCaseNum,
//		'testCaseName' : TestCaseName,
//		'description' : Description,
//		'type' : Type,
//		'parent':parent
//	};
//	dojo.xhrPost({
//		url : 'addTestCase',
//		postData : dojo.toJson(gridData),
//		handleAs : "json",
//		headers : {
//			'Content-Type' : 'application/json',
//		},
//		load : function(response) {
//
//			alert('JSON received from server:' + response);
//			var newStore, args = {}, grid = dijit.byId("gridContainer");
//			args.url = "TFgridDetails/" + testfunctionName;
//			newStore = new dojo.data.ItemFileWriteStore(args);
//			grid.setStore(newStore);
//			refreshTreeInformation();
//		},
//		error : function(error) {
//			console.log(error);
//			alert('error occurred, check the console!');
//		}
//	});
//
//}


//addTestCase
function addTestCase() {

	dojo.xhrPost({
		url : 'addTestCase/'+testfunctionName,
		form:dojo.byId("myForm"),
		
		load : function(response) {
			alert('JSON received from server:' + response);
			var newStore, args = {}, grid = dijit.byId("gridContainer");
			args.url = "TFgridDetails/" + testfunctionName;
			newStore = new dojo.data.ItemFileWriteStore(args);
			grid.setStore(newStore);
			refreshTreeInformation();
			removeTestCases();
			document.getElementById("myForm").reset();
		},
		error : function(error) {
			console.log(error);
			alert('error occurred, check the console!');
		}
	});
	

}



function addTestCaseFields11() {

	dojo.xhrPost({
		url : 'addTestCaseFields/'+ testfunctionName+"/"+Tcparent,
		form:dojo.byId("myForm1"),
		
		load : function(response) {
			alert('JSON received from server:' + response);
			var newStore, args = {}, grid = dijit.byId("grid");
			args.url = "TCgridDetails/" + testfunctionName+"/"+Tcparent;
			newStore = new dojo.data.ItemFileWriteStore(args);
			grid.setStore(newStore);
			refreshTreeInformation();
			removeTestCaseFields();
			document.getElementById("myForm1").reset();
		},
		error : function(error) {
			console.log(error);
			alert('error occurred, check the console!');
		}
	});
	

}

////add TestCase Fields
//function addTestCaseFields() {
//
//	var FieldName = document.getElementById("FieldName").value;
//	var Fieldtype = document.getElementById("Fieldtype").value;
//	var Permission = document.getElementById("Permission").value;
//	var FieldValue = document.getElementById("FieldValue").value;
//	var Xpath = document.getElementById("Xpath").value;
//	var gridData = {
//		'fieldName' : FieldName,
//		'fieldType' : Fieldtype,
//		'permission' : Permission,
//		'fieldValue' : FieldValue,
//		'xpath':Xpath
//	};
//	dojo.xhrPost({
//		url : 'addTestCaseFields/'+ testfunctionName+"/"+Tcparent,
//		postData : dojo.toJson(gridData),
//		handleAs : "json",
//		headers : {
//			'Content-Type' : 'application/json',
//		},
//		load : function(response) {
//
//			alert('JSON received from server:' + response);
//			var newStore, args = {}, grid = dijit.byId("grid");
//			args.url = "TCgridDetails/" + testfunctionName+"/"+Tcparent;
//			newStore = new dojo.data.ItemFileWriteStore(args);
//			grid.setStore(newStore);
//			refreshTreeInformation();
//		},
//		error : function(error) {
//			console.log(error);
//			alert('error occurred, check the console!');
//		}
//	});
//
//}








//refresh Tree
dojo.extend(dijit.Tree, {
	refreshModel : function() {

		// reset the itemNodes Map
		this._itemNodesMap = {};

		// remove the rootNode
		if (this.rootNode) {
			this.rootNode.destroyRecursive();
		}

		// reload the tree
		this._load();
	}
});

//refresh Tree fun
function refreshTreeInformation() {
	var treeObject = dijit.byId("tree");
	treeObject.refreshModel();
}

//Tree load  fun
function treeLoad() {
	usGov = dojo.store
			.JsonRest({
				target : "TreeLoading/",
				mayHaveChildren : function(object) {
					// see if it has a children property
					return "children" in object;
				},
				getChildren : function(object, onComplete, onError) {
					// retrieve the full copy of the object(important to sending parent)
					this.get(object.name + "/" + object.nodeType).then(
							function(fullObject) {
								// copy to the original object so it has the children array as well.
								object.children = fullObject.children;
								// now that full object, we should have an array of children
								onComplete(fullObject.children);
							}, function(error) {
								// an error occurred, log it, and indicate no children
								console.error(error);
								onComplete([]);
							});
				},
				getRoot : function(onItem, onError) {
					// get the root object, we will do a get() and callback the result
					this.get("CLIP/root").then(onItem, onError);
				},
				getLabel : function(object) {
					// just get the name
					return object.name;
				},

				pasteItem : function(child, oldParent, newParent, bCopy,
						insertIndex) {
					var store = this;
					store
							.get(oldParent.id)
							.then(
									function(oldParent) {
										store
												.get(newParent.id)
												.then(
														function(newParent) {
															var oldChildren = oldParent.children;
															dojo
																	.some(
																			oldChildren,
																			function(
																					oldChild,
																					i) {
																				if (oldChild.id == child.id) {
																					oldChildren
																							.splice(
																									i,
																									1);
																					return true; // done
																				}
																			});
															store
																	.put(oldParent);
															newParent.children
																	.splice(
																			insertIndex || 0,
																			0,
																			child);
															store
																	.put(newParent);
														},
														function(error) {
															alert("Error occurred (this demo is not hooked up to a real database, so this is expected): "
																	+ error);
														});
									});
				},
				put : function(object, options) {
					//this.onChange(object);
					this.onChildrenChange(object, object.children);
					this.onChange(object);
					return dojo.store.JsonRest.prototype.put.apply(this,
							arguments);
				}
			});
	tree = new dijit.Tree({
		model : usGov
	}, "tree"); // make sure you have a target HTML element with this id
	tree.startup();

	//tree click function
	dojo.connect(tree, "onClick", function createStore(object) {
		var mid = object.id;
		var mname = object.name;
		var nodeType = object.nodeType;
		var parent = object.parent;
		alert(mid + "," + mname + "," + nodeType);
		send(mname,parent);

		//if parent node clicked
		if (nodeType == "parent") {
			dojo.style(dojo.byId("accordion"), "display", "block");
			dojo.style(dojo.byId("accordion1"), "display", "none");
			dojo.style(dojo.byId("middlepane"), "display", "block");
			dojo.style(dojo.byId("middlepane1"), "display", "none");
			var xhrArgs = {
				url : "TFgridDetails/" + mname,
				handleAs : "json",
				headers : {
					"Content-Type" : "application/json"
				},
				load : function(data) {
					var newData = {
						items : data.items
					};

					var newStore = new dojo.data.ItemFileWriteStore({
						data : newData,
						id : "dataStoreId"
					});

					var grid = dijit.byId("gridContainer");

					grid.setStore(newStore);
					grid.startup();
				},
				error : function(error) {
					alert("Error");
				}
			};
			var deferred = dojo.xhrGet(xhrArgs);
			var text1 = dijit.byId("TFname"), text2 = dijit
					.byId("TFdescription"), text3 = dijit.byId("TFstatistics");
			var xhrArgs11 = {
				url : "TFdescription/" + mname,
				handleAs : "json",

			};
			var deferred11 = dojo.xhrPost(xhrArgs11);

			deferred11.addCallback(this, function(value) {
				// put retrieved picklists in select.options[]
				var books = value.books;
				text1.setValue(books[0].name);
				text2.setValue(books[1].name);
				text3.setValue(books[2].name);
			});

		}

		//if children node clicked
		else if (nodeType == "children") {
			dojo.style(dojo.byId("accordion1"), "display", "block");
			dojo.style(dojo.byId("accordion"), "display", "none");
			dojo.style(dojo.byId("middlepane1"), "display", "block");
			dojo.style(dojo.byId("middlepane"), "display", "none");
			var xhrArgs = {
				url : "TCgridDetails/" + mname + "/" + parent,
				handleAs : "json",
				headers : {
					"Content-Type" : "application/json"
				},
				load : function(data) {
					var newData = {
						items : data.items
					};

					var newStore = new dojo.data.ItemFileWriteStore({
						data : newData,
						id : "dataStoreId"
					});
					var grid = dijit.byId("grid");
					grid.setStore(newStore);
					grid.startup();

					grid.startup();
				},
				error : function(error) {
					alert("Error");
				}
			};
			var deferred = dojo.xhrGet(xhrArgs);

			var text1 = dijit.byId("TCname"), text2 = dijit
					.byId("TCdescription");
			var xhrArgs21 = {
				url : "TcDescription/" + mname + "/" + parent,
				handleAs : "json",

			};
			var deferred21 = dojo.xhrPost(xhrArgs21);

			deferred21.addCallback(this, function(value) {
				// put retrieved picklists in select.options[]
				var books = value.books;
				text1.setValue(books[0].name);
				text2.setValue(books[1].name);
			});

		}

	});
}

//welcome page
function welcomePageLoad() {
	dojo.style(dojo.byId("accordion"), "display", "block");
	dojo.style(dojo.byId("accordion1"), "display", "none");
	dojo.style(dojo.byId("middlepane"), "display", "block");
	dojo.style(dojo.byId("middlepane1"), "display", "none");
	var mid = "Tf01";
	var xhrArgs = {
		url : "TFgridDetails/" + mid,
		handleAs : "json",
		headers : {
			"Content-Type" : "application/json"
		},
		load : function(data) {
			var newData = {
				items : data.items
			};

			var dataStore = new dojo.data.ItemFileWriteStore({
				data : newData,
				id : "dataStoreId"
			});
			var gridStructure = [ {
				field : "TestCaseNum",
				name : "TestCase No.",
				width : "10%",
				noresize : true
			}, {
				field : "TestCaseName",
				name : "TestCase Name",
				width : "20%",
				noresize : true,
				editable : true
			}, {
				field : "Description",
				name : "Description",
				width : "20%",
				noresize : true,
				editable : true
			}, {
				field : "Type",
				name : "Type",
				width : "20%",
				noresize : true,
				editable : true
			}, ];

			var grid = new dojox.grid.DataGrid({
				store : dataStore,
				rowSelector : "20px",
				structure : gridStructure,
				style : 'width:100%;height:80%;',
			}, "gridContainer");
			grid.startup();
		},
		error : function(error) {
			alert("Error");
		}
	};
	var deferred = dojo.xhrGet(xhrArgs);

	var text1 = dijit.byId("TFname"), text2 = dijit.byId("TFdescription"), text3 = dijit
			.byId("TFstatistics");
	var xhrArgs11 = {
		url : "TFdescription/" + mid,
		handleAs : "json",

	};
	var deferred11 = dojo.xhrPost(xhrArgs11);

	deferred11.addCallback(this, function(value) {
		// put retrieved picklists in select.options[]
		var books = value.books;
		text1.setValue(books[0].name);
		text2.setValue(books[1].name);
		text3.setValue(books[2].name);
	});
	var mid1 = "Tc01";
	var mparent = "Tf01"
	var xhrArgs1 = {
		url : "TCgridDetails/" + mid1 + "/" + mparent,
		handleAs : "json",
		headers : {
			"Content-Type" : "application/json"
		},
		load : function(data) {
			var newData = {
				items : data.items
			};

			var dataStore = new dojo.data.ItemFileWriteStore({
				data : newData,
				id : "dataStoreId"
			});
			var gridStructure = [ {
				field : "FieldName",
				name : "Field Name",
				width : "10%",
				noresize : true
			}, {
				field : "Fieldtype",
				name : "Field Type",
				width : "20%",
				noresize : true,
				editable : true
			}, {
				field : "Permission",
				name : "Permission",
				width : "20%",
				noresize : true,
				editable : true
			}, {
				field : "FieldValue",
				name : "Field Value",
				width : "20%",
				noresize : true,
				editable : true
			}, {
				field : "Xpath",
				name : "Xpath",
				width : "20%",
				noresize : true,
				editable : true
			}, ];

			var grid = new dojox.grid.DataGrid({
				store : dataStore,
				rowSelector : "20px",
				structure : gridStructure,
				style : 'width:100%;height:80%;',
			}, "grid");
			grid.startup();
		},
		error : function(error) {
			alert("Error");
		}
	};
	var deferred1 = dojo.xhrGet(xhrArgs1);
}


//adding rows dynamically for TestCases

function addTestCases(divName) {
	var newdiv = document.createElement('div');
	newdiv.innerHTML = "<table> <tr><td><input data-dojo-type='dijit/form/TextBox'name='TestCaseNum' id='TestCaseNum' class='textbox1' ></td><td><input data-dojo-type='dijit/form/TextBox' name='TestCaseName' id='TestCaseName' class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox' name='Description' id='Description' class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox' name='Type' id='Type' class='textbox1'></td>	</tr></table>"
	 document.getElementById(divName).appendChild(newdiv)


}

//adding rows dynamically for TestCasesFields
function addTestCaseFields(divName) {
	var newdiv = document.createElement('div');
	newdiv.innerHTML = "<table><tr><td><input data-dojo-type='dijit/form/TextBox' name='FieldName' id='FieldName' class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox' name='Fieldtype' id='Fieldtype' class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox' name='Permission' id='Permission'class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox'	name='FieldValue' id='FieldValue' class='textbox1'></td><td><input data-dojo-type='dijit/form/TextBox' name='Xpath' id='Xpath'class='textbox1'></td></tr></table>"
	 document.getElementById(divName).appendChild(newdiv)


}


//removing rows dynamically for TestCases
function removeTestCases() {
	var exDiv = document.getElementById("hello");
	var fc = exDiv.firstChild;
	while (fc) {
		exDiv.removeChild(fc);
		fc = exDiv.firstChild;
	}
}

//removing rows dynamically for TestCaseFields
function removeTestCaseFields() {
	var exDiv = document.getElementById("hello1");
	var fc = exDiv.firstChild;
	while (fc) {
		exDiv.removeChild(fc);
		fc = exDiv.firstChild;
	}
}

